<template>
  <a-space align="center" style="margin-bottom:16px; width:100%;justify-content:center;">
    <a-form :model="formSearch" layout="inline" @submit="doSearch">
      <a-form-item field="title" label="标题">
        <a-input v-model="formSearch.title" placeholder="请输入标题" allow-clear />
      </a-form-item>
      <a-form-item field="content" label="内容">
        <a-input v-model="formSearch.content" placeholder="请输入内容关键字" allow-clear />
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit">搜索</a-button>
          <a-popover trigger="click" title="列设置">
            <template #content>
              <a-checkbox-group v-model="selectedKeys" :options="columnOptions" />
            </template>
            <a-button>列设置</a-button>
          </a-popover>
        </a-space>
      </a-form-item>
    </a-form>
  </a-space>

  <a-table
    :columns="visibleColumns"
    :data="dataList"
    :pagination="{
      showTotal:true,
      pageSize:searchParams.pageSize,
      current:searchParams.current,
      total
    }"
    @page-change="onPageChange"
  >
    <template #tags="{ record }">
      <a-tag v-for="tag in record.tagList||[]" :key="tag">{{ tag }}</a-tag>
    </template>
    <template #createTime="{ record }">
      {{ dayjs(record.createTime).format("YYYY-MM-DD HH:mm") }}
    </template>
    <template #updateTime="{ record }">
      {{ dayjs(record.updateTime).format("YYYY-MM-DD HH:mm") }}
    </template>
    <template #optional="{ record }">
      <a-space>
        <a-button type="text" @click="goToEdit(record.id)">编辑</a-button>
        <a-button status="danger" @click="doDelete(record.id)">删除</a-button>
      </a-space>
    </template>
  </a-table>
</template>

<script setup lang="ts">
import { ref, reactive, watchEffect, computed } from "vue";
import dayjs from "dayjs";
import type { CheckboxOption } from "@arco-design/web-vue";
import {
  listMyPostVoByPageUsingPost,
  deletePostUsingPost,
} from "@/api/postController";
import API from "@/api";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";

// 列定义
interface ColDef { key:string; title:string; dataIndex?:string; slotName?:string; }
const allColumns: ColDef[] = [
  { key:"id",           title:"ID",           dataIndex:"id" },
  { key:"title",        title:"标题",         dataIndex:"title" },
  { key:"content",      title:"内容",         dataIndex:"content" },
  { key:"tags",         title:"标签",         slotName:"tags" },
  { key:"favourNum",    title:"收藏数",       dataIndex:"favourNum" },
  { key:"thumbNum",     title:"点赞数",       dataIndex:"thumbNum" },
  { key:"createTime",   title:"创建时间",     dataIndex:"createTime", slotName:"createTime" },
  { key:"updateTime",   title:"更新时间",     dataIndex:"updateTime", slotName:"updateTime" },
  { key:"optional",     title:"操作",         slotName:"optional" },
];
// 默认列 keys
const defaultKeys = ["title","content","tags","createTime","optional"];
const selectedKeys = ref<string[]>([...defaultKeys]);
const columnOptions = computed<CheckboxOption[]>(() =>
  allColumns.map(c => ({ label:c.title, value:c.key }))
);
const visibleColumns = computed(() =>
  allColumns
    .filter(c => selectedKeys.value.includes(c.key))
    .map(c => {
      const col:any = { title:c.title, key:c.key };
      if(c.dataIndex) col.dataIndex = c.dataIndex;
      if(c.slotName)  col.slotName  = c.slotName;
      return col;
    })
);

// 搜索 & 分页
const formSearch = ref<Partial<API.PostQueryRequest>>({});
const initSearch = { current:1, pageSize:10 };
const searchParams = ref<Partial<API.PostQueryRequest>>({...initSearch});
const dataList = ref<API.PostVO[]>([]);
const total = ref(0);

// 拉数据
async function loadData(){
  const res = await listMyPostVoByPageUsingPost(searchParams.value);
  if(res.data.code===0){
    dataList.value = res.data.data?.records||[];
    total.value    = res.data.data?.total||0;
  } else {
    message.error("获取失败："+res.data.message);
  }
}
function doSearch(){
  searchParams.value = { ...initSearch, ...formSearch.value };
}
function onPageChange(page:number){
  searchParams.value = { ...searchParams.value, current: page };
}
async function doDelete(id?:number){
  if(!id) return;
  const res = await deletePostUsingPost({ id });
  if(res.data.code===0){
    message.success("删除成功");
    loadData();
  } else {
    message.error("删除失败："+res.data.message);
  }
}
watchEffect(loadData);

// 跳到编辑页
const router = useRouter();
function goToEdit(id?:number){
  if(id) router.push(`/post/edit/${id}`);
}
</script>
